package com.dianban.controller.shaliangjie;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dianban.base.ResultCode;
import com.dianban.base.ResultVo;
import com.dianban.config.redis.RedisConstant;
import com.dianban.config.redis.RedisUtil;
import com.dianban.controller.BaseController;
import com.dianban.entity.FacePayConfig;
import com.dianban.entity.FacePayStoreOrder;
import com.dianban.entity.ShopUser;
import com.dianban.entity.User;
import com.dianban.service.*;
import com.dianban.utils.DateUtils;
import com.dianban.utils.UserUtils;
import com.dianban.utils.XiaomaiguiUtils;
import com.dianban.weixin.util.WechatUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wujh
 * @create 2020/1/10
 */
@Api(value = "ApiOrderController", description = "沙粮姐订单控制器")
@RestController
@RequestMapping(value = "${interfacePath}/shaliangjie/order/")
public class ApiSljOrderController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(ApiSljOrderController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private WxUserService wxUserService;
    @Autowired
    private FacePayStoreOrderService facePayStoreOrderService;
    @Autowired
    private FacePayStoreConsumeLogService facePayStoreConsumeLogService;
    @Autowired
    private StoreGuideService storeGuideService;
    @Autowired
    private ShoproOrderService shoproOrderService;
    @Autowired
    private ShopUserService shopUserService;
    @Autowired
    private JwShoproGoodsService jwShoproGoodsService;
    @Autowired
    private FacePayConfigService facePayConfigService;

    @ApiOperation(notes = "waitPay", httpMethod = "POST", value = "待支付订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userToken", value = "用户token", required = true, paramType = "header", dataType = "string"),
    })
    @RequestMapping(value = "waitPay", method = RequestMethod.POST)
    public ResultVo waitPay(HttpServletRequest request, HttpServletResponse response) {
        String userToken = request.getHeader(UserUtils.USER_TOKEN);
        String key = RedisConstant.USER_TOKEN_KEY + userToken;
        User user = (User) RedisUtil.get(key);
        if (user == null) {
            return ResultVo.error(ResultCode.ERROR, "请求头userToken过期");
        }
        Long userId = user.getId();
        // 存在待支付的订单是，则返回订单编号，提示用户先支付，前端接收到订单编号跳转到支付接口
        List<FacePayStoreOrder> facePayStoreOrderList = facePayStoreOrderService.findVerifyList(userId, null, null, 10, "50");
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("order", facePayStoreOrderList);
        return ResultVo.success(resultMap, "成功");
    }

    @ApiOperation(notes = "submitOpen", httpMethod = "POST", value = "开门订单提交")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userToken", value = "用户token", required = true, paramType = "header", dataType = "string"),
            @ApiImplicitParam(name = "storeId", value = "店铺ID", required = true, paramType = "query", dataType = "string"),
    })
    @RequestMapping(value = "submitOpen", method = RequestMethod.POST)
    public ResultVo submitOpen(Long storeId, HttpServletRequest request, HttpServletResponse response) {
        String userToken = request.getHeader(UserUtils.USER_TOKEN);
        String key = RedisConstant.USER_TOKEN_KEY + userToken;
        User user = (User) RedisUtil.get(key);
        if (user == null) {
            return ResultVo.error(ResultCode.ERROR, "请求头userToken过期");
        }
        Long userId = user.getId();
        // 判断有没openid,没有的话不让开门
        User _user = userService.findById(userId);
        if (_user != null && StringUtils.isEmpty(_user.getOpenid())) {
            return ResultVo.error(ResultCode.ERROR, "账号异常无法开门");
        }
        if (storeId == null) {
            return ResultVo.error(ResultCode.ERROR, "店铺ID不能为空");
        }
        Object objRedis = RedisUtil.get("doorOpen-" + user.getMobile());
        if (objRedis != null) {
            return ResultVo.error(ResultCode.ERROR, "正在选购中");
        }
        // 存在待支付的订单是，则返回订单编号，提示用户先支付，前端接收到订单编号跳转到支付接口
        //List<FacePayStoreOrder> facePayStoreOrderList = facePayStoreOrderService.findVerifyList(userId,storeId, null, 10,"50");
        // 不能带id
        List<FacePayStoreOrder> facePayStoreOrderList = facePayStoreOrderService.findVerifyList(userId, null, null, 10, "50");
        if (facePayStoreOrderList.size() > 0) {
            FacePayStoreOrder facePayStoreOrder = facePayStoreOrderList.get(0);
            Map<String, Object> content = new HashMap<>();
            content.put("orderNumber", facePayStoreOrder.getOrderNumber());
            //content.put("money", facePayStoreOrder.getMoney());
            //content.put("goodinfo", facePayStoreOrder.getGoodinfo());
            //return ResultVo.error(ResultCode.ERROR430, content);
            return ResultVo.success(content, "成功");
        }
        String orderNumber = facePayStoreOrderService.buildOrderNumber("SLJ");

        // 生成订单
        ShopUser shopUser = shopUserService.findByStoreId(storeId);
        Long shopUserId = shopUser.getId();

        FacePayStoreOrder facePayStoreOrder = new FacePayStoreOrder();
        facePayStoreOrder.setStoreId(storeId);
        facePayStoreOrder.setStoreManagerId(shopUserId);
        facePayStoreOrder.setUserId(userId);
        facePayStoreOrder.setOrderNumber(orderNumber);
        facePayStoreOrder.setMoney(null);
        facePayStoreOrder.setPayStatus(null);
        facePayStoreOrder.setCommissionStatus(null);
        facePayStoreOrder.setHasVerifyCount(0);
        facePayStoreOrder.setTakenewHasVerifyCount(0);
        facePayStoreOrder.setMemo("沙粮姐线上套餐");
        facePayStoreOrder.setPayType("50");
        facePayStoreOrder.setCanVerifyCount(0);
        facePayStoreOrder.setTakenewVerifyCount(0);
        facePayStoreOrderService.insert(facePayStoreOrder);

        // 调用开门接口
        try {
            List<FacePayConfig> facePayConfigList = facePayConfigService.find(110, 1, storeId);
            for (FacePayConfig facePayConfig : facePayConfigList) {
                String name = facePayConfig.getName();
                JSONObject open = XiaomaiguiUtils.open(name, orderNumber, user.getMobile());
                if (open != null) {
                    String code = String.valueOf(open.get("code"));
                    if (StringUtils.isNotBlank(code) && "200".equalsIgnoreCase(code)) {
                        // 开门成功
                        RedisUtil.set("doorOpen-" + user.getMobile(), orderNumber, 30);
                    } else {
                        return ResultVo.error(ResultCode.ERROR, "自助售卖柜暂未开机或在维护中！");
                    }
                } else {
                    return ResultVo.error(ResultCode.ERROR, "自助售卖柜暂未开机或在维护中！");
                }

            }
        } catch (Throwable e) {
            e.printStackTrace();
            logger.error("调用小卖柜开门异常-{}", e.getMessage());
        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("orderNumber", null);
        return ResultVo.success(resultMap, "成功");
    }

    @ApiOperation(notes = "updateClose", httpMethod = "POST", value = "关门订单更新")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "data", value = "data", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "sign", value = "sign", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "appid", value = "appid", required = true, paramType = "query", dataType = "string"),
    })
    @RequestMapping(value = "updateClose", method = RequestMethod.POST)
    public Map<String, Object> updateClose(String data, String sign, String appid, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>();
        // 验证签名

        //转换data数据
        JSONObject jsonObject = JSON.parseObject(data);
        String orderNo = jsonObject.getString("orderNo");
        FacePayStoreOrder facePayStoreOrder = facePayStoreOrderService.findByOrderNumber(orderNo);
        if (facePayStoreOrder == null) {
            result.put("code", "400");
            result.put("msg", "订单编号错误");
            result.put("data", "");
            return result;
        }
        JSONArray orderinfoArray = JSON.parseArray(jsonObject.getString("orderinfo"));
        BigDecimal money = BigDecimal.ZERO;
        String goodinfo = "";
        for (int i = 0; i < orderinfoArray.size(); i++) {
            JSONObject orderinfo = orderinfoArray.getJSONObject(i);
            // totalfee 是 string总售价 单位分
            // goodsname 是 string商品名称
            String totalfeeStr = orderinfo.getString("totalfee");
            BigDecimal totalfee = new BigDecimal(totalfeeStr).divide(new BigDecimal(100), 2, RoundingMode.UP);
            money = money.add(totalfee);
            String goodsname = orderinfo.getString("goodsname");
            if (StringUtils.isNotBlank(goodsname)) {
                if (StringUtils.isBlank(goodinfo)) {
                    goodinfo = goodsname;
                } else {
                    goodinfo = goodinfo + "、" + goodsname;
                }
            }
        }
        facePayStoreOrder = new FacePayStoreOrder();
        facePayStoreOrder.setOrderNumber(orderNo);
        facePayStoreOrder.setMoney(money);
        facePayStoreOrder.setPayStatus(10);
        facePayStoreOrder.setCommissionStatus(10);
        facePayStoreOrder.setOrderinfo(data);
        facePayStoreOrder.setGoodinfo(goodinfo);
        facePayStoreOrderService.updateSlj(facePayStoreOrder);
        // 推送一条待支付消息
        try {
            FacePayStoreOrder order = facePayStoreOrderService.findByOrderNumber(orderNo);
            if (order != null) {
                User user = userService.findById(order.getUserId());
                if (user != null && StringUtils.isNotBlank(user.getOpenid())) {
                    WechatUtils.wait_pay(user.getOpenid(), orderNo, DateUtils.format(new Date(order.getCreatetime() * 1000), DateUtils.Y_M_D_H_M_S), String.valueOf(money), "有订单等待支付，如您已支付，请忽略本消息！");
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }

        // { "code": "200", "msg": "success", "data": {} }
        result.put("code", "200");
        result.put("msg", "success");
        result.put("data", "");
        return result;
    }

}
